package com.oceansoft.core.interceptor;

import java.io.IOException;
import java.io.Writer;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oceansoft.core.common.constant.Constant;

/**
 * 会话过期拦截
 * 
 * @author chenw
 * 
 */
public class SessionFilter implements Filter {

	private Set<String> excludeUrl;

	@Override
	public void destroy() {
		this.excludeUrl = null;
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		Object obj = request.getSession().getAttribute(Constant.LOGIN_USER);
		String url = request.getRequestURI().toString().toLowerCase();
		boolean isAjax = url.endsWith(".json") || url.endsWith(".xml");
//		obj = null;
		if (null != obj) {
			chain.doFilter(servletRequest, servletResponse);
		} else {
			boolean rt1 = url.matches("^/\\w*/profile/login.html(;jsessionid=\\w*)?$");
			boolean rt2 = url.matches("^/\\w*/profile/auth.json$");
			boolean rt3 = url.matches("^/\\w*/profile/exit.html$");
			boolean rt5 = url.matches("^/\\w*/profile/sso.html$");
			boolean rt4 = url.matches("^/\\w*/resource$");
			if (rt1 || rt2 || rt3 ||rt4|| rt5) {
				chain.doFilter(servletRequest, servletResponse);
			} else {
				String ajaxHeader = request.getHeader("x-requested-with");
				if (isAjax || null != ajaxHeader && ajaxHeader.equalsIgnoreCase("XMLHttpRequest")) {
					response.setHeader("sessionState", "0");
					response.setContentType("text/html");
					Writer writer = response.getWriter();
					writer.write("{sessionState:0}");
					writer.flush();
					writer.close();
				} else {
					request.setAttribute("target", url);
					request.getRequestDispatcher(Constant.PAGE_TIMIE_OUT).forward(request, response);
				}
			}
		}
	}

	@SuppressWarnings("unused")
	private boolean excludeUrl(HttpServletRequest request, String code) {
		String uri = request.getRequestURI();
		if (uri.equals("/uums/profile/login/" + code + "/") || uri.equals("/uums/")) {
			return true;
		}
		return false;
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String _url = config.getInitParameter("exculdeUrl");
		if (null != excludeUrl) {
			String[] _arr = _url.replaceAll("\\s", "").split(",");
			for (String str : _arr) {
				getExcludeUrl().add(str);
			}
		}
	}

	public Set<String> getExcludeUrl() {
		return excludeUrl;
	}

	public void setExcludeUrl(Set<String> excludeUrl) {
		this.excludeUrl = excludeUrl;
	}

}
